import datetime
from flask import Blueprint, make_response, request, jsonify
import jwt
from tool.config import config
import requests

config = config.get_config("config.toml")

auth_bp = Blueprint('auth', __name__)

# 假设目标认证服务地址
AUTH_SERVER_BASE = f"http://{config['SYNCSERVER']['SERVER_IP']}:{config['SYNCSERVER']['SERVER_PORT']}"

@auth_bp.route("/api/register", methods=["POST"])
def proxy_register():
    data = request.get_json()
    if not data.get("registerName") or not data.get("registerPassword"):
        return jsonify({"error": "用户名和密码不能为空"}), 400

    try:
        resp = requests.post(f"{AUTH_SERVER_BASE}/api/register", json=data, timeout=5)
        return jsonify(resp.json()), resp.status_code
    except requests.exceptions.RequestException as e:
        return jsonify({"error": f"认证服务连接失败: {str(e)}"}), 502


@auth_bp.route("/api/login", methods=["POST"])
def proxy_login():
    data = request.get_json()
    if not data.get("loginUsername") or not data.get("loginPassword"):
        return jsonify({"error": "用户名和密码不能为空"}), 400

    try:
        resp = requests.post(f"{AUTH_SERVER_BASE}/api/login", json=data, timeout=5)
        return resp

    except requests.exceptions.RequestException as e:
        token = jwt.encode({"user": data.get("loginUsername"), "exp": datetime.datetime.utcnow() + datetime.timedelta(hours=1)},
                           config["FILE_SYSTEM"]["JWT_SECRET_KEY"], algorithm="HS256")

        resp = make_response(jsonify({"msg": "登录成功"}),201)
        resp.set_cookie("token", token, max_age=100000000, httponly=False)  # 设置 HttpOnly=True 更安全
        return resp
